<?php

namespace app\common\service;

use app\data\util\HttpUtil;
use app\data\util\MqQueueName;
use app\order\logic\OrderListLogic;
use app\order\logic\OrderServiceLogic;
use app\shop\logic\ShopLogic;
use app\common\service\UploadService;
use app\systems\logic\MqTaskPushLogic;
use think\facade\Config;
use think\facade\Db;
class TiktokPackageApiService
{
    private $basic_url          = null;
    private $package_path        = null;

    public function __construct()
    {
        $this->basic_url    = Config('Logisticskey.TIKTOK.basic_url');
        $this->package_path = Config('Logisticskey.TIKTOK.package_path');
    }

    /**
     * @desc  创建包ID生成面单
     * @date  2024/3/21 0021
     * @param $order
     * @return array|\think\response\Json
     * @author ligang
     */
    public function createPackage($order)
    {
        $shop = Db::name('shops')->where('id',$order['shop_id'])->find();
        $data['order_id'] = $order['order_id'];
        $sign     = $shop['app_secret'] . '' . $this->package_path . 'app_key' . $shop['app_key'] . 'shop_cipher' . $shop['cipher'] . 'timestamp' . time() . '{"order_id":"' . $order['order_id'] . '"}' . $shop['app_secret'];
        $sign     = hash_hmac('sha256', $sign, $shop['app_secret']);
        $url      = $this->basic_url . $this->package_path . "?app_key=" . $shop['app_key'] . "&shop_cipher=" . $shop['cipher'] . "&sign=" . $sign . "&timestamp=" . time();
        $info     = HttpUtil::tikPostUrl($url, $data, $shop['access_token']);
        if ($info['code'] != 0 || !isset($info['data']['package_id'])) {
            return [
              'code' => 201,
              'msg' => "失败",
              'data' => json_encode($info,JSON_UNESCAPED_UNICODE),
            ];
        } else {
            return [
               'code' => 200,
               'msg' => "成功",
               'data' => $info['data']['package_id'],
            ];
        }
    }

    /**
     * @desc  根据包ID获取doc_url下载到本地
     * @date  2024/3/21 0021
     * @param $order
     * @return array|\think\response\Json
     * @author ligang
     */
    public function downDocUrl($order)
    {

            htmlLog(['params'=>$order],OPERATE_LOG . date('Ym') . '/downDocUrlParams/' . date('Ymd') . '.txt');
            $shop = Db::name('shops')->where('id',$order['shop_id'])->find();
            $package_id = $order['package_id'];
            $sign = $shop['app_secret'] . '' . $this->package_path . '/' . $package_id . '/shipping_documents' . 'app_key' . $shop['app_key'] . 'document_sizeA6document_typeSHIPPING_LABEL_AND_PACKING_SLIPshop_cipher' . $shop['cipher'] . 'timestamp' . time() . '' . $shop['app_secret'];
            $sign = hash_hmac('sha256', $sign, $shop['app_secret']);
            $url  = $this->basic_url . $this->package_path . '/' . $package_id . '/shipping_documents' . "?app_key=" . $shop['app_key'] . "&shop_cipher=" . $shop['cipher'] . "&sign=" . $sign . "&timestamp=" . time() . '&document_size=A6&document_type=SHIPPING_LABEL_AND_PACKING_SLIP';
            $data = HttpUtil::tikGetUrl($url, $shop['access_token']);
            if ($data['code'] != 0 || !isset($data['data']['doc_url'])) {
                htmlLog(['order_id'=>$order['order_id'],'package_id'=>$package_id,'msg'=>$data['message']],OPERATE_LOG . date('Ym') . '/downDocUrl/' . date('Ymd') . '.txt');
                Db::name('order')->where('order_id',$order['order_id'])->update([ 'shipping_documents_status'=>'5']);
                Db::name('order_shipping_documents_log')->insert(
                    [
                        'batch_id'           =>$order['batch_id'],
                        'order_id'           =>$order['order_id'],
                        'shop_id'            =>$order['shop_id'],
                        'status'             =>5,
                        'msg'                =>$data['message']??'',
                        'package_id'         =>$order['package_id'],
                        'created_time'       =>date("Y-m-d H:i:s", time()),
                    ]
                );
                return true;
            }

            $doc_url   = $data['data']['doc_url'];
            //地址上传到阿里云OSS;
            $service   = new UploadService();
            $BASE_PATH = dirname(__DIR__, 1);
            $local_dir = $BASE_PATH . '/runtime/package/';
            if (!is_dir($local_dir)) {
                mkdir($local_dir, 0777, true);
            }
            //存入本地地址;
            $local_dir_file = $local_dir . $order['order_id'] . '.pdf';
            file_put_contents($local_dir_file, file_get_contents($doc_url));

            //上传阿里云地址;
            $shop_name = $shop['name'];
            $shop_name = str_replace(' ', '', $shop_name);
            $ossDir    = 'package/' . date('ymd') . '/' . $shop_name . '/' . $order['order_id'] . '.pdf';
            $res       = $service->uploads($local_dir_file, $ossDir);
            $res_url   = $res['info']['url']??'';
            //上传后清除本地数据
            unlink($local_dir_file);
            if($res){
                Db::name('order')->where('order_id',$order['order_id'])->update(
                    [
                        'waybill_status'           =>'hidden',
                        'shipping_documents_status'=>'4',
                        'shipping_documents'       =>$res_url,
                    ]
                );

                Db::name('order_shipping_documents_log')->insert(
                    [
                        'batch_id'           =>$order['batch_id']??'',
                        'order_id'           =>$order['order_id']??'',
                        'shop_id'            =>$order['shop_id']??'',
                        'status'             =>4,
                        'msg'                =>'创建面单地址成功',
                        'package_id'         =>$order['package_id']??'',
                        'shipping_documents' =>$res_url,
                        'created_time'       =>date("Y-m-d H:i:s", time()),
                    ]
                );
        }
        return true;
    }




    /**
     * @desc  根据包ID获取doc_url下载到本地
     * @date  2024/3/21 0021
     * @param $order
     * @return array|\think\response\Json
     * @author ligang
     */
    public function downChangeDocUrl($order)
    {

        $shop = Db::name('shops')->where('id',$order['shop_id'])->find();
        $package_id = Db::name('order_shipping_documents_log')->where(['order_id'=>$order['order_id'],'status'=>2])->value('package_id');
        $sign = $shop['app_secret'] . '' . $this->package_path . '/' . $package_id . '/shipping_documents' . 'app_key' . $shop['app_key'] . 'document_sizeA6document_typeSHIPPING_LABEL_AND_PACKING_SLIPshop_cipher' . $shop['cipher'] . 'timestamp' . time() . '' . $shop['app_secret'];
        $sign = hash_hmac('sha256', $sign, $shop['app_secret']);
        $url  = $this->basic_url . $this->package_path . '/' . $package_id . '/shipping_documents' . "?app_key=" . $shop['app_key'] . "&shop_cipher=" . $shop['cipher'] . "&sign=" . $sign . "&timestamp=" . time() . '&document_size=A6&document_type=SHIPPING_LABEL_AND_PACKING_SLIP';
        $data = HttpUtil::tikGetUrl($url, $shop['access_token']);
        if ($data['code'] != 0 || !isset($data['data']['doc_url'])) {
            htmlLog(['order_id'=>$order['order_id'],'package_id'=>$package_id,'msg'=>$data['message']],OPERATE_LOG . date('Ym') . '/downDocUrl/' . date('Ymd') . '.txt');
            Db::name('order')->where('order_id',$order['order_id'])->update([ 'shipping_documents_status'=>'5']);
            Db::name('order_shipping_documents_log')->insert(
                [
                    'batch_id'           =>$order['batch_id'],
                    'order_id'           =>$order['order_id'],
                    'shop_id'            =>$order['shop_id'],
                    'status'             =>5,
                    'msg'                =>$data['message']??'',
                    'package_id'         =>$package_id,
                    'created_time'       =>date("Y-m-d H:i:s", time()),
                ]
            );
            return true;
        }

        $doc_url   = $data['data']['doc_url'];
        //地址上传到阿里云OSS;
        $service   = new UploadService();
        $BASE_PATH = dirname(__DIR__, 1);
        $local_dir = $BASE_PATH . '/runtime/package/';
        if (!is_dir($local_dir)) {
            mkdir($local_dir, 0777, true);
        }
        //存入本地地址;
        $local_dir_file = $local_dir . $order['order_id'] . '.pdf';
        file_put_contents($local_dir_file, file_get_contents($doc_url));

        //上传阿里云地址;
        $shop_name = $shop['name'];
        $shop_name = str_replace(' ', '', $shop_name);
        $ossDir    = 'package/' . date('ymd') . '/' . $shop_name . '/' . $order['order_id'] . '.pdf';
        $res       = $service->uploads($local_dir_file, $ossDir);
        $res_url   = $res['info']['url']??'';
        //上传后清除本地数据
        unlink($local_dir_file);
        if($res){
            Db::name('order')->where('order_id',$order['order_id'])->update(
                [
                    'waybill_status'           =>'hidden',
                    'shipping_documents_status'=>'4',
                    'shipping_documents'       =>$res_url,
                ]
            );

            Db::name('order_shipping_documents_log')->insert(
                [
                    'batch_id'           =>$order['batch_id']??'',
                    'order_id'           =>$order['order_id']??'',
                    'shop_id'            =>$order['shop_id']??'',
                    'status'             =>4,
                    'msg'                =>'创建面单地址成功',
                    'package_id'         =>$order['package_id']??'',
                    'shipping_documents' =>$res_url,
                    'created_time'       =>date("Y-m-d H:i:s", time()),
                ]
            );
        }
        return true;
    }




    /**
     * @desc 获取运单费用
     * @date  2024-04-26
     * @author luckyXiong
     */
    public function get_shipping_fee($info){
        $orderId = $info['order_id']??'';
        $order_ids = json_encode([$orderId],true);
        $shop    = Db::name('order')
            ->alias('a')
            ->leftJoin('ba_shops s', 's.id = a.shop_id')
            ->where('a.order_id',$orderId )
            ->field('s.app_key, s.app_secret,s.cipher,s.access_token')
            ->find();
        $baseUrl  = Config('Logisticskey.TIKTOK.basic_url');
        $path     = Config('Logisticskey.TIKTOK.orders_fulfillment_path').$orderId.'/shipping_services/query';
        $sign     = $shop['app_secret'] . '' . $path . 'app_key' . $shop['app_key'] . 'shop_cipher' . $shop['cipher'] . 'timestamp' . time() . '{"order_line_item_ids":'.$order_ids.'}' . $shop['app_secret'];
        $sign     = hash_hmac('sha256', $sign, $shop['app_secret']);
        $url      = $baseUrl . $path . "?app_key=" . $shop['app_key'] . "&shop_cipher=" . $shop['cipher'] . "&sign=" . $sign . "&timestamp=" . time();
        $return   = HttpUtil::tikPostUrl($url,['order_line_item_ids'=>[$orderId]], $shop['access_token']);
        if (!isset($return['data']['shipping_services']) || empty($return['data']['shipping_services']))  return [201, false, '暂无数据!',null];
        $orderinfo = $return['data']['shipping_services'];
        $shipping_prices     = array_column($orderinfo,'price');
        $filtered_prices = array_map(function($price) {
            return str_replace('$', '', $price);
        }, $shipping_prices);
        $shipping_price_min  = min($filtered_prices);
        Db::name('order')->where('order_id',$orderId)->update(['shipping_price'=>$shipping_price_min]);
        return  true;
    }



    /**
     * @desc 同步订单数据
     * @date  2024-04-26
     * @author luckyXiong
     */
    public function get_operate_order($info){
        $orderId = $info['order_id']??'';
        $shop_id = $info['shop_id']??'';
        $order_info = Db::name('order')->where(['order_id' => $orderId])->find();
        if($order_info)  return  true;
        $shop    = Db::name('shops')->where('id',$shop_id)->find();
        $tik_info = Config::get('Logisticskey.' . 'TIKTOK');
        $baseUrl  = $tik_info['basic_url'];
        $path     = $tik_info['orders_info_path'];
        $sign     = $shop['app_secret'] . '' . $path . 'app_key' . $shop['app_key'] . 'ids' . $orderId . 'shop_cipher' . $shop['cipher'] . 'timestamp' . time() . '' . $shop['app_secret'];
        $sign     = hash_hmac('sha256', $sign, $shop['app_secret']);
        $url      = $baseUrl . $path . "?app_key=" . $shop['app_key'] . "&shop_cipher=" . $shop['cipher'] . "&sign=" . $sign . "&timestamp=" . time() . '&ids=' . $orderId;
        $return   = HttpUtil::tikGetUrl($url, $shop['access_token']);
        if (!isset($return['data']['orders'][0]) || empty($return['data']['orders'][0]))  return true;
        $orderinfo = $return['data']['orders'][0];
        $orderinfo['shop_id']    = $shop_id;
        if($shop['time_zone']){
            $orderinfo['createtime'] = $orderinfo['create_time'] - $shop['time_zone'] * 3600;
        }else{
            $orderinfo['createtime'] = $orderinfo['create_time'];
        }
        //获取写入数据组装;
        $arr_info = (new OrderListLogic())->get_arr_info($orderinfo);

        //批量写入数据;
        Db::name('order')->insert($arr_info['order_arr']);
        Db::name('order_info')->insertAll($arr_info['order_info_arr']);
        Db::name('order_append')->insert($arr_info['order_append_arr']);
        return  true;
    }






}
